#!/usr/bin/env python
#
# Copyright 2009 Benjamin Davis
#
# This file is part of resistencia.
#
# resistencia is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# resistencia is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with resistencia.  If not, see <http://www.gnu.org/licenses/>.

import sys
import mud.dungeons
import mud.net
import mud.persistence

from mud.options import *

if __name__ == "__main__":
    try:
        print "Loading dungeon from file '" + os.path.join(SAVE_PREFIX, 'data') + "'...",
        # Attempt to load dungeon from file
        dungeon = mud.persistence.load(DUNGEON)
        # If it doesn't exist yet (i.e. first time running server)
        if dungeon is None:
            # Create a new dungeon
            dungeon = mud.dungeons.Resistencia()
            print 'failure.'
        else:
            print 'success.'
        
        print "dungeon: "
        print
        # Print a map of the levels
        print dungeon.draw_map()
        
        # If port is specified as a parameter
        if len(sys.argv) > 1:
            # Use specified port
            PORT = int(sys.argv[1])
        # If not, server uses default port (in mud.options)
        # Start serving
        mud.net.main(PORT, dungeon)
        
    # If the user presses Ctrl+C
    except KeyboardInterrupt:
        # Exit silently
        pass

    except:
        raise

    # Save the current game state
    print "Saving dungeon to file '" + os.path.join(SAVE_PREFIX, 'data') + "'...",
    if mud.persistence.save('resistencia', dungeon):
        print 'success.'
    else:
        print 'failure.'
